<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
	const CREATED_AT = 'insert_time';
    const UPDATED_AT = 'update_time';
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_admin';

    protected $primaryKey = 'admin_id';

    public $timestamps = false;

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = [
        'admin_name','admin_tel',
        'admin_passwd','admin_pic',
        'admin_ip','region',
        'insert_time','update_time'
    ];

    public function add($data)
    {
        $this_ = $this;
        if(!empty($data['admin_id'])){
            $this_ = $this->where('admin_id',$data['admin_id'])->first();
        }
        $this_->admin_name = $data['name'];
        $this_->admin_tel = $data['tel'];
        $this_->status = $data['status'];
        $this_->region = $data['region'];
        $this_->power_name = $data['power_name'] ?? '普通权限';
        $this_->insert_time = time();
        if(!empty($data['setpassword'])){
            $this_->admin_passwd = md5(md5($data['setpassword']));
        }
        if(is_array($data['power'])){
            $this_->power = json_encode($data['power']);
        }else{
            $this_->power = $data['power'];
            $this_->power_name = '管理员';
        }

        if($this_->save()){
            return ['success'=>true,'code'=>'000','message'=>'保存成功','data'=>[
                'admin_id'=>$this_->admin_id
            ]];
        }else{
            return ['success'=>false,'code'=>'006','message'=>'保存出错，请稍后再试'];
        }
    }
}
